# Create your views here.
from models import Carthasitem
from models import BuyItemForm
from models import Item
from models import ChangeNumberForm
from django.core.urlresolvers import reverse
from django.shortcuts import HttpResponseRedirect
from models import Cart
from django.forms import DateField
from django.template.response import TemplateResponse
from models import Carthasitem
from pdb import Pdb
import datetime
from django.db.models import Sum 
from models import Cart_Context


#===============================================================================
# COUPLING!!!!!!!!!!!!!
# TODO:
'''
decouple cart and check-out apps
when i login() in check-out-app, i call a function called login() in cart-app.
Instead, refactor: remove that call and instead make invarient in the cart app.
1.if the user is logged in, he does not have a cart in his request.session
    use django signals
'''
'''
When the user logs in, if he has a cart it is saved to the database (as the user's cart)
In other words, this function must always be called when the user logs in.
It is called from the check_out app, from the login method there.
'''
#===============================================================================
def login(request,id):
    if request.session.get('cart',default=False):
        cart=Cart.objects.get(pk=id)
        cart.user=request.user
        cart.save()
        del request.session['cart']
        
def get_cart(request):
    if request.user.is_authenticated():
        user_carts=Cart.objects.filter(user=request.user)
        if user_carts.exists():
            latest_cart=user_carts.latest('date')
            return latest_cart
        else:
            cart=Cart(user=request.user,date=datetime.datetime.now())
            cart.save()
            return cart
    else:
        cart=request.session.get('cart',False)
        if cart:
            cart=Cart.objects.get(pk=cart)
        else:
            cart=Cart.objects.create(date=datetime.datetime.now())
            cart.save()
            request.session['cart']=cart.pk
        return cart
# id is the item.pk for which to either change qantity or add to the cart
def add(request, id):
    pdb=Pdb()
    if request.method=='POST':
        form=BuyItemForm(request.POST)
        if form.is_valid():
            number_of_items=form.cleaned_data['number']
            
            item=Item.objects.get(pk=id)
            latest_cart=get_cart(request)
            cart_has_item=None
            if item in latest_cart.items.all():
                changenumber(request,Carthasitem.objects.get(cart=latest_cart,item=item).pk)
                return HttpResponseRedirect(reverse('seecart'))
            else:
                cart_has_item=Carthasitem(item=item,cart=latest_cart,number=number_of_items)
                cart_has_item.save()
            
            return HttpResponseRedirect(reverse('confirm', args=[form.cleaned_data['number'],id]))
        else:
            return TemplateResponse(request,'store/itemdetails.html',{'form':form,'item':item})
    #TODO: give error: only post accepted
    else:
        pass
def add_promotion(request,promotion):
    pass
def see(request):
    if request.user.is_authenticated():
        carts=Cart.objects.filter(user=request.user).order_by('date')
        if carts.exists():
            cart_context=[]
            for user_cart in carts:
                #pdb.set_trace()
                cart_context.append(Cart_Context(user_cart))
            return TemplateResponse(request,'cart/carts.html',{'cart_contexts':cart_context,'total':100})
        else:
            return TemplateResponse(request,'cart/carts.html',{})
    else:
        context=None
        cart_context=[]
        if request.session.get('cart',default=False):
            context=Cart_Context(Cart.objects.get(pk=request.session.get('cart')))
            cart_context.append(context)
        #TODO: calculate total
        #insert it into a tuple with cart_context: tuple(total,cart_context)
        #in the template carts do:
        # for total, cart context
        # include cart.html with item_list=cart_context total=total
        return TemplateResponse(request,'cart/carts.html',{'cart_contexts':cart_context,'total':100})
    
    
def confirm(request, quantity,id):
    item=Item.objects.get(pk=id)
    return TemplateResponse(request,'cart/confirmation.html',{ 'quantity':quantity,'item':item})

#delete cart_has_item. If the cart is empty delete it also.
def delete_item(request, cart_has_item):
    cart=cart_has_item.cart
    cart_has_item.delete()
    if cart.is_empty():
        cart.delete()
        # if he is not authenticated, the session will hold his cart
        # if he is authenticated, then the session will be empty. see login() above.
        if not request.user.is_authenticated():
            del request.session['cart']


# Precondition. cart id is given as input
# Postcondition: If the user submitted > 0 for the item number in the form, the new value will be saved
#                If the user has submitted 0 for the form, the item will be deleted from the cart.
                        #If the cart is empty it wil also be deleted when i call the delete_item method
def changenumber(request,id):
    cart_has_item=Carthasitem.objects.get(pk=id)
    form=BuyItemForm(request.POST,instance=cart_has_item)
    if form.is_valid():
        if form.cleaned_data['number']==0:
            delete_item(request,cart_has_item)
        elif form.cleaned_data['number']>0:
            form.save()
        else:
            pass
            #TODO: produce error

        
